<?php

namespace app\post\controllers;

use mini\{Session, Validator};

class Index
{
    /**
     * 显示帖子内容
     */
    public function show()
    {
        $post_id = segment(3, 'int');
        $post    = model('post')->find($post_id);

        // 查询不到帖子内容，则显示 404 页面
        if ( !$post ) {
            return abort(404);
        }

        $user_id  = session('user_id');
        $user     = model('user')->find($user_id);

        // 记住当前地址，用于登录或注册后返回当前页
        $current_url = url('/post/show/').$post_id;
        Session::set('backToLink', $current_url);

        $data = [
            'page_title' => '帖子',
            'post'       => $post,
            'user'       => $user,
            'custom_js'  => [
                'medium-zoom.min.js',
                'gifffer.js',
            ],
        ];

        return template('public', $data);
    }

    /**
     * 删除帖子
     */
    public function del()
    {
        login_check();

        $post_id = segment(3, 'int');

        if (REQUEST_TYPE === 'post' && $user->id === $post->user_id) {
            try {
                $post = db('post');
                $post->where('id = ?', $post_id)->delete();

                return json('删除成功', 'success');
            } catch (\Throwable $th) {
                return json('删除失败', 'error');
            }
        }
    }

    /**
     * 提交表单数据
     */
    public function submit()
    {
        if (REQUEST_TYPE === 'post') {

            // 获取表单数据
            $data['content'] = post('content');
            // 验证规则
            $rules  = [
                'content' => ['required', '1,400', '内容应为 1-200 个字符'],
            ];
            // 验证
            $validate = new Validator($data, $rules, true);
            $verify = $validate->check();

            if (!$verify) {
                return json($validate->error);
            }

            try {
                $save = model('post')->store($data);

                return json('发帖成功', 'success');
            } catch (\Throwable $th) {
                return json($th->getMessage());
            }
        }
    }
}
